﻿using Newtonsoft.Json;
using Omabar.Common;
using Omabar.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace Omabar.CMS.Handler
{
    /// <summary>
    /// UpLoadImage 的摘要说明
    /// </summary>
    public class UpLoadImage : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            RESP_Info info = new RESP_Info();
            try
            {
                context.Response.ContentType = "text/plain";

                string rFolder = "UpLoad/" + DateTime.Now.ToString("yyyy-MM-dd");
                string pFolder = context.Server.MapPath("../" + rFolder);
                if (!System.IO.Directory.Exists(pFolder))
                {
                    System.IO.Directory.CreateDirectory(pFolder);
                }

                HttpPostedFile hpFile = context.Request.Files[0];
                string fileName = DateTime.Now.Ticks + hpFile.FileName;
                hpFile.SaveAs(pFolder + "/" + fileName);
                
                info.Success = true;
                info.Url = AppConst.Domain + rFolder + "/" + fileName;
                info.Title = "提示";
                info.Tip = "上传图片成功";
            }
            catch (System.Web.HttpException ex)
            {
                Tom.Net.Log.LogManager.Error("上传图片失败,图片大小超过限制", ex);
                info.Success = false;
                info.Title = "错误";
                info.Tip = "上传失败，图片大小超过限制";
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                Tom.Net.Log.LogManager.Error("上传图片失败,图片大小超过限制", ex);
                info.Success = false;
                info.Title = "错误";
                info.Tip = "上传失败，图片大小超过限制";
            }
            catch (Exception ex)
            {
                Tom.Net.Log.LogManager.Error("上传图片失败", ex);
                info.Success = false;
                info.Title = "错误";
                info.Tip = "上传失败";
            }

            context.Response.Write(JsonConvert.SerializeObject(info));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}